import BlindBox, { IPrize } from '../models/BlindBox';
import { Request, Response } from 'express';
import upload from '../middlewares/upload';
import moment from 'moment'
import { log } from 'console';
import _ from 'lodash'

// 增加盲盒
export const addBlindBox = async (req: Request, res: Response) => {
    upload.single('image')(req, res, async (error: any) => {
        if (error) {
            return res.status(500).json({ message: error.message });
        }

        try {
            // 提取除图片外的其他表单数据
            const { name, description, price, stock, productInfo, rule, sellBeginTime, sellEndTime, longDesc, balanceCost } = req.body;

            // 创建新的盲盒对象
            const newBlindBox = new BlindBox({
                name,
                description,
                image: req.file ? req.file.path : '', // 获取上传的图片路径
                price,
                stock,
                balanceCost,
                productInfo, // 这应该是一个 JSON 字符串
                rule, // 确保这是有效的规则格式
                sellBeginTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                sellEndTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                longDesc,
                createdAt: moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedAt: moment().format('YYYY-MM-DD HH:mm:ss')
            });

            await newBlindBox.save();
            res.status(201).json({
                status: 'ok',
                message: '新增盲盒成功！',
                data: _.omit(newBlindBox.toObject(), ['longDesc'])
            });
        } catch (error: any) {
            res.status(500).json({ message: error.message });
        }
    });
};

// 删除盲盒
export const deleteBlindBox = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const blindBox = await BlindBox.findByIdAndDelete(id);
        if (!blindBox) {
            return res.status(404).json({ message: '盲盒未找到' });
        }
        res.json({ message: '盲盒删除成功' });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 更新盲盒
export const updateBlindBox = async (req: Request, res: Response) => {
    upload.single('image')(req, res, async (error: any) => {
        if (error) {
            return res.status(500).json({ message: error.message });
        }

        try {
            const { _id } = req.body;
            let updateData = req.body;

            // 如果有新的图片上传，则更新图片路径
            if (req.file) {
                updateData.image = req.file.path;
            } else {
                delete updateData.image
            }

            // 更新 updatedAt 字段
            updateData.updatedAt = moment().format("YYYY-MM-DD HH:mm:ss");

            const updatedBlindBox = await BlindBox.findByIdAndUpdate(_id, updateData, { new: true });
            if (!updatedBlindBox) {
                return res.status(404).json({ message: '盲盒未找到' });
            }

            res.json({
                status: 'ok',
                message: '更新盲盒成功！',
                data: _.omit(updatedBlindBox.toObject(), ['longDesc'])
            });
        } catch (error: any) {
            res.status(500).json({ message: error.message });
        }
    });
};

// 查询单个盲盒
export const getBlindBoxById = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const blindBox = await BlindBox.findById(id);
        if (!blindBox) {
            return res.status(404).json({ message: '盲盒未找到' });
        }
        res.json(blindBox);
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 分页查询所有盲盒
export const getBlindBoxes = async (req: Request, res: Response) => {
    try {
        const page = parseInt(req.query.page as string) || 1;
        const limit = parseInt(req.query.limit as string) || 10;
        const skipIndex = (page - 1) * limit;
        const blindBoxes = await BlindBox.find().skip(skipIndex).limit(limit).select('-longDesc');
        const total = await BlindBox.countDocuments();

        // 计算是否还有下一页
        const hasNextPage = page * limit < total;
        // 如果还有下一页，则生成 nextToken，否则为 null
        const nextToken = hasNextPage ? page + 1 : null;

        res.json({
            total,
            page,
            limit,
            nextToken,
            data: blindBoxes
        });
    } catch (error: any) {
        res.status(500).json({
            status: 'falid',
            message: error.message
        });
    }
};
